package com.sebiotec.glp.limoapp.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.SystemClock;

public class TimersUtils {
    public static void setKeepAliveAlarm(Context context, boolean interVal) {
        // 防止4.4以下的重复执行setRepeating
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT && interVal) {
            return;
        }

        // 循环时间
        int TIME_INTERVAL = 60 * 1000;
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent local = new Intent(context, RepetitionService.class);
//        Intent local = new Intent(context, "ALERT_KEEP_ACTION");
        PendingIntent pendingIntent = PendingIntent.getService(context, 999, local,
                PendingIntent.FLAG_UPDATE_CURRENT);

        // 此处必须使用SystemClock.elapsedRealtime，否则闹钟无法接收
        long triggerAtMillis = SystemClock.elapsedRealtime();

        // 更新开启时间
        if (interVal) {
            triggerAtMillis += TIME_INTERVAL;
        }

        // pendingIntent 为发送广播
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis,
                    pendingIntent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, pendingIntent);
        } else {// api19以前还是可以使用setRepeating重复发送广播
            alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, TIME_INTERVAL,
                    pendingIntent);
        }
        return;
    }
}

